﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;

namespace Agents.Admin
{
    // This is the edit page for an existing agent
    public partial class EditCustomer : System.Web.UI.Page
    {
        protected void Page_Load(object sender, EventArgs e)
        {
            //spilling the information of agent only if we just entered the page.
            if (!Page.IsPostBack)
            {
                //retrieving and spilling agents name from previouse page
                int Id = Int32.Parse(Request.QueryString["customerId"]);

                //creating a query object for accessing the database.
                Queries queries = new Queries();
                Clients client = queries.GetClient(Id);
                
                //retrieving and spilling the clients information from database
                nameTxtbox.Text = client.Name;

                txtCity.Text = client.City;
                txtStreet.Text = client.Street;
                txtStreetNum.Text = client.StreetNum;
                phoneTxtbox.Text = client.Phone;
                emailTxtbox.Text = client.EMail;

                // Bind the regions list
                cmbArea.DataSource = queries.GetAllRegions();
                cmbArea.DataValueField = "Id";
                cmbArea.DataTextField = "Name";

                // Choose the selected region after binding
                cmbArea.DataBound += new EventHandler(
                    (s, ev) => { cmbArea.Items.FindByValue(client.Region.ToString()).Selected = true; });

                cmbArea.DataBind();

                creditTxtbox.Text = client.CreditCardLevel;
                contactMenTxtbox.Text = client.ContactPerson;
                hpTxtbox.Text = client.CP;

                // Bind the regions list
                cmbArea.DataSource = queries.GetAllRegions();
                cmbArea.DataValueField = "Id";
                cmbArea.DataTextField = "Name";

                // Choose the selected sales type after binding
                cmbArea.DataBound += new EventHandler(
                    (s, ev) => { cmbArea.Items.FindByValue(client.Region.ToString()).Selected = true; });

                cmbArea.DataBind();

                active.Selected = (client.Status == "פעיל");
                nonActive.Selected = !active.Selected;
                if (client.Priority != "-1")
                {
                    priorityChkBox.Checked = true;
                    priorityTxtbox.Text = client.Priority;
                }
            }
        }

        //this function is activatedif the administrater pressed the update button.
        protected void okBtn_Click(object sender, EventArgs e)
        {
            //retrieving and spilling agents name from previouse page
            int Id = Int32.Parse(Request.QueryString["customerId"]);

            //creating a query object for accessing the database.
            Queries queries = new Queries();
            Clients client = queries.GetClient(Id);

            //making sure all text boxes have been filled
            if (nameTxtbox.Text == "" || txtCity.Text == "" || txtStreet.Text == "" ||
                txtStreetNum.Text == "" || phoneTxtbox.Text == "" || emailTxtbox.Text == ""
                || cmbArea.SelectedItem == null || creditTxtbox.Text == "" || contactMenTxtbox.Text == "" ||
                 hpTxtbox.Text == "" || cmbPricesType.SelectedItem == null ||
                 (active.Selected == false && nonActive.Selected == false) ||
                (priorityChkBox.Checked && priorityTxtbox.Text == ""))
            {
                //if something is missing- print apropriot message to screan.
                empty.Text = ".קיימים שדות ריקים. אנא, מלא את כולם";
            }
            else
            {   //making sure the edited client does not clame a new name that exists in the database.
                if (queries.CheckClientNameColision(client.Id, client.Name))
                {
                    // Disable the buttons so the user can't interfere
                    backBtn.Enabled = false;
                    deleteBtn.Enabled = false;
                    okBtn.Enabled = false;

                    string priority = "-1";
                    string status = "פעיל";
                    if (priorityChkBox.Checked)
                        priority = priorityTxtbox.Text;
                    if (nonActive.Selected)
                    {
                        status = "לא פעיל";
                    }

                    //adding the new client into our database
                    queries.EditClient(client.Id, nameTxtbox.Text, txtCity.Text, txtStreet.Text,
                        txtStreetNum.Text, phoneTxtbox.Text,
                        emailTxtbox.Text, priority, Int32.Parse(cmbArea.SelectedValue),
                        creditTxtbox.Text, contactMenTxtbox.Text, hpTxtbox.Text,
                        Int32.Parse(cmbPricesType.SelectedValue), status, client.x, client.y);

                    // Announce success and wait for 2 seconds before redirecting
                    empty.Text = "הלקוח עודכן בהצלחה";
                    redirectionTimer.Enabled = true;
                }
                //if the client already exists- print apropriate message to screan
                else
                {
                    nameExists.Text = "שם הלקוח כבר נמצא במערכת";
                }
            }
        }

        //function for redirecting the administrater back to his home page.
        protected void backBtn_Click1(object sender, EventArgs e)
        {
            Response.Redirect("~/Admin/ChooseCustomer.aspx");
        }

        /// <summary>
        /// Redirect back to the admin menu after a few seconds
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        protected void redirectionTimer_Tick(object sender, EventArgs e)
        {
            Response.Redirect("~/Admin/AdminMenu.aspx");
        }
    }
}